<?php
/**
 * --------------------------------------------------------------
 * 管理员控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\Admin as AdminModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupAccess as AuthAccessModel;

class Admin extends AdminBase
{
    /**
     * 管理员列表
     */
    public function index()
    {
        $map  = $this->getSimpleSearchMap();
        $list = AdminModel::where($map['where'])
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => '管理员列表'
        ]);
        return $this->fetch();
    }

    /**
     * 新增
     */
	public function add()
	{
	    if ($this->request->isPost()) {
			$data     = $this->request->post();
			
			$validate = validate('Admin');
            if (!$validate->scene('add')->check($data)) {
        		$this->error($validate->getError());
        	}
			
            $group            = $data['group'];
        	$pwdinfo          = encrypt_password(sha1($data['password']));
        	$data['password'] = $pwdinfo['password'];
			$data['encrypt']  = $pwdinfo['encrypt'];
        	unset($data['group']);
            $result = AdminModel::create($data);
            $list   = [];
			
            if ($result) {
                foreach ($group as $k => $v){
                    $list[$k]['aid']      = $result;
                    $list[$k]['group_id'] = $v;
                }
				$AccessModel = new AuthAccessModel();
                $AccessModel->saveAll($list);
            }
            return $result ? $this->success('新增成功', url('index')) : $this->error('新增失败');
        } else {
			$groups = AuthGroupModel::where(['status' => 1])->select();

			$this->assign([
                'groups' => $groups,
                'title'  => '新增管理员'
            ]);
        	return $this->fetch();
        }
	}

    /**
     * 编辑
     */
	public function edit()
	{
		$id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');
		if ($id == 1) $this->error('禁止操作超级管理员账号。');
		
		$AccessModel = new AuthAccessModel();
    	if ($this->request->isPost()) {
            $data     = $this->request->post();
			
            $validate = validate('Admin');
            if (!$validate->scene('edit')->check($data)) {
        		$this->error($validate->getError());
        	}
			
            $group  = $data['group'];
			if ($data['password']) {
                $pwdinfo          = encrypt_password(sha1($data['password']));
                $data['password'] = $pwdinfo['password'];
                $data['encrypt']  = $pwdinfo['encrypt'];
			} else {
			    unset($data['password']);
			}
        	unset($data['group']);
            $result = AdminModel::update($data);
            if ($result) {
                // 先删除角色-用户关联表中的相关数据
                $falg = $AccessModel::where('aid', $id)->delete();
                $list = [];
                foreach ($group as $k => $v){
                    $list[$k]['aid']      = $id;
                    $list[$k]['group_id'] = $v;
                }
                $AccessModel->saveAll($list);
            }
            return $result ? $this->success('编辑成功', url('index')) : $this->error('编辑失败');
    	} else {
            $info        = AdminModel::get($id);
            $groups      = AuthGroupModel::where(['status' => 1])->select();
            $thisgroup   = $AccessModel::where('aid', $id)->column('group_id');
            $this->assign([
                'info'      => $info,
				'groups'    => $groups,
				'thisgroup' => $thisgroup,
                'title'     => '编辑管理员'
            ]);
    		return $this->fetch();
    	}
	}
	
	/**
	 * 删除
	 * @param integer $ids id值
	 */
	public function del($ids = 0)
	{
        (int) $ids || $this->error('参数错误');
		if (in_array(1, $ids)) $this->error('禁止操作超级管理员账号');

        $map = ['id' => $ids];

		// 删除用户与角色之间的关系
        AuthAccessModel::where(['aid', 'in', $ids])->delete();
		$result = AdminModel::where($map)->delete();
        return $result ? $this->success('删除成功') : $this->error('删除失败');
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        in_array('1', $ids) && $this->error('禁止操作超级管理员账号');
        
        $map  = ['id' => $ids];
        $info = AdminModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }
}